package com.example.administrator.szb.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.CodeBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.http.OnResultListener;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.SPUtils;
import com.example.administrator.szb.util.Toasts;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by D N on 2017/10/24.
 */

public class WebViewActivity extends BaseActivity {

    @Bind(R.id.webview_webview)
    WebView webviewWebview;
    private int wz_id = 0;
    private int user_id;
    String info="";
    String title = "";
    String image = "";
    private ImageView shoucang;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview_activity);
        ButterKnife.bind(this);
        shoucang = (ImageView) findViewById(R.id.shoucang);
        shoucang.setVisibility(View.VISIBLE);
        SampleApplicationLike.getActivitiesInstance().add(this);
        initToolbarThreeImage(R.id.webview_toolbar_include, "资讯详情", R.drawable.share, new Callback() {
            @Override
            public void doSomeThing() {
                share();
            }
        });

        hasIntent();
        initWebView();
        shoucang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //收藏
                requestShouCang();
            }
        });
    }

    private void hasIntent() {
        wz_id = getIntent().getIntExtra("wz_id",-1);
        title = getIntent().getStringExtra("title");
        image = getIntent().getStringExtra("image");
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void initWebView() {
        user_id = SampleApplicationLike.getUserloginInstance().getId();
        info = "";
        if (user_id <= 0){
         info = URLAddress.URL_WZXQ+"article_id="+wz_id;
        }else {
            info = URLAddress.URL_WZXQ+"article_id="+wz_id+"&users_id="+user_id;
        }
        WebSettings webSettings = webviewWebview.getSettings();
//支持缩放，默认为true。
        webSettings .setSupportZoom(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//让缩放显示的最小值为起始
        webviewWebview.setInitialScale(5);
//调整图片至适合webview的大小
        webSettings .setUseWideViewPort(true);
// 缩放至屏幕的大小
        webSettings .setLoadWithOverviewMode(true);
//设置默认编码
        webSettings .setDefaultTextEncodingName("utf-8");
////设置自动加载图片
        webSettings .setLoadsImagesAutomatically(true);


        webviewWebview.loadUrl(info);
        webviewWebview.setWebChromeClient(new WebChromeClient());

//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webviewWebview.getSettings().setJavaScriptEnabled(true);
        //    添加js对象(必要)
        webviewWebview.addJavascriptInterface(new JavaScriptInterfaceZX(this), "loginActionAndroid");
        webviewWebview.setWebViewClient(new MyWebViewClient());
//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT){
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setBlockNetworkImage(false);
    }

    private void shouQuan() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE, Manifest.permission.READ_LOGS, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SET_DEBUG_APP, Manifest.permission.SYSTEM_ALERT_WINDOW, Manifest.permission.GET_ACCOUNTS, Manifest.permission.WRITE_APN_SETTINGS};
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {


    }


    private void share() {
        UMImage thumb = new UMImage(this, image);
        UMWeb web = new UMWeb(""+info+"&app=1");
        web.setTitle(""+title);//标题
        web.setThumb(thumb);  //缩略图
        try {
            web.setDescription(""+title.substring(0,8));//描述
        }catch (Exception e){
            web.setDescription(""+title);//描述
        }

        new ShareAction(WebViewActivity.this)
                .withMedia(web)
                .setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ,SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN,SHARE_MEDIA.WEIXIN_CIRCLE)
                .setCallback(new UMShareListener() {
                    @Override
                    public void onStart(SHARE_MEDIA share_media) {
                        //Toasts.show(WebViewActivity.this, "start", Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void onResult(SHARE_MEDIA share_media) {
                        Toasts.show(WebViewActivity.this, "分享成功", Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                        Toasts.show(WebViewActivity.this, "" + throwable.toString(), Toast.LENGTH_SHORT);
                    }

                    @Override
                    public void onCancel(SHARE_MEDIA share_media) {

                    }
                })
                .open();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        Log.d("pdf", "onActivityResult: why");
       // shouQuan();
    }

    private class MyWebViewClient extends WebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //  html加载完成之后，调用js的方法
            imgReset();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            // 加载网页失败时处理  如：
            Toasts.show(WebViewActivity.this, ""+description, Toast.LENGTH_SHORT);
        }
    }

    private void imgReset() {
        webviewWebview.loadUrl("javascript:(function(){"
                + "var objs = document.getElementsByTagName('img'); "
                + "for(var i=0;i<objs.length;i++)  " + "{"
                + "var img = objs[i];   "
                + "    img.style.width = '100%';   "
                + "    img.style.height = 'auto';   "
                + "}" + "})()");
    }


    private class JavaScriptInterfaceZX{
        Activity activity;

        public JavaScriptInterfaceZX(Activity activity) {
            this.activity = activity;
        }

        @JavascriptInterface
        public void postMessage(Object o) {
            Log.d("pdf", "postMessage: +++++++han to");
            //Toasts.show(activity,"test", Toast.LENGTH_SHORT);
            startActivity(new Intent(activity,LoginNewActivity.class));
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onRestart() {
        super.onRestart();
        initWebView();
    }
    public void requestShouCang(){
        if (!(SPUtils.isLogin())){
            startActivity(new Intent(WebViewActivity.this,LoginNewActivity_two.class));
            return;
        }
        Map<String,Object> params = new HashMap<>();
        params.put("code", HttpUtil.getParam());
        params.put("id", SPUtils.getUserId()+"");
        params.put("article_id",wz_id+"");
        HttpUtils.post(activity,URLAddress.URLBASE + URLAddress.URL_QXSCZX, params, new OnResultListener() {
            @Override
            public void onSuccess(int requestCode, String str) {
                CodeBean codeBean = JSON.parseObject(str,new TypeReference<CodeBean>(){});
                if (codeBean.getCode()==0){
                    //收藏成功
                    codeBean.setMsg("收藏成功");
                    shoucang.setImageResource(R.mipmap.sc_white_yes);
                }else {
                //取消收藏成功
                    codeBean.setMsg("已取消收藏");
                    shoucang.setImageResource(R.mipmap.sc_white_no);
                }
                DialogUtil.showToast(WebViewActivity.this,codeBean.getMsg()+"");
            }

            @Override
            public void onFailure(int requestCode, String str) {

            }
        });
    }
}
